/*
 * @Author: Zhang Kai
 * @Date: 2021-10-29 15:34:12
 * @LastEditors: Zhang Kai
 * @LastEditTime: 2022-06-17 11:35:55
 * @FilePath: /metricsx-standard-ui/src/views/indexManage/modifiermanage/components/createForm.tsx
 */
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  watchEffect,
  watch
} from 'vue';

import API from '@/services';
import { setFieldsValue } from '@/utils/util';
import '../style/createForm.scss';

const createForm = defineComponent({
  name: 'CreateForm',
  props: {
    createFormRef: {
      type: Object,
      default: () => {}
    },
    errorData: {
      type: Object,
      default: () => []
    },
    isEdits: {
      type: Boolean,
      default: () => false
    },
    editData: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['handleClose', 'submit'],
  setup(props, { slots, attrs, emit }) {
    let model: any = reactive({
      type: '',
      cnName: '',
      enName: '',
      subjectId: '',
      businessMeaning: '',
      remarks: '',
      codeSegment: ''
    });

    /* 修饰词分组list */
    const gourpOptions = ref();

    const rule: any = reactive({
      type: [
        {
          required: true,
          message: '请选择修饰词类型',
          trigger: 'blur'
        }
      ],
      cnName: [
        {
          required: true,
          message: '请输入修饰词名称',
          trigger: 'blur'
        }
      ],
      enName: [
        {
          required: true,
          message: '请输入修饰词英文名称',
          trigger: 'blur'
        }
      ],
      subjectId: [
        {
          required: true,
          message: '请选择主题',
          trigger: 'change'
        }
      ],
      businessMeaning: [
        {
          required: true,
          message: '请输入业务含义',
          trigger: 'blur'
        }
      ],
      groupId: [
        {
          required: true,
          message: '请选择修饰词分组',
          trigger: ['blur', 'change']
        }
      ]
    });

    const modifierTypeData: any = ref([
      { label: '统计周期', value: 1 },
      { label: '业务范围', value: 2 }
    ]);

    const subjectList: any = ref([]);

    //获取主题list

    /* 主题 */
    const getSubjectsFirstLevel = async () => {
      try {
        const { code, data } = await API.subject.getSubjectsFirstLevel();
        if (code === 200 && Array.isArray(data)) {
          subjectList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 名称重复字段及文案校验 */
    const errCheck = (label: string) => {
      const errKey = props.errorData?.map((v: any) => v.error_field);
      if (errKey?.includes(label)) {
        const errInfo: any = props.errorData?.filter(
          (v: any) => v.error_field === label
        );
        return new String(errInfo[0].error_msg);
      }
      return false;
    };

    /* 分组list */
    const getGroupList = async () => {
      try {
        const { code, data }: any = await API.modifier.getModifierGroupRoot();
        if (code === 200 && Array.isArray(data?.children)) {
          gourpOptions.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    watch(
      () => props.editData,
      () => {
        if (Object.keys(props.editData).length > 0) {
          const { editData } = props;
          setFieldsValue(model, editData);
          //去除头一级"全部"
          editData?.path.shift();
          model.groupId = editData?.path;
        }
      },
      { immediate: true }
    );

    onMounted(() => {
      getSubjectsFirstLevel();
      getGroupList();
    });

    return () => {
      const { createFormRef, isEdits } = props;
      return (
        <div class="CreateForm">
          <el-form
            ref={createFormRef}
            rules={rule}
            label-position={'right'}
            label-width="110px"
            model={model}
          >
            <el-form-item label="修饰词类型:" prop="type">
              <el-select
                size="large"
                v-model={model.type}
                filterable
                placeholder="请选择"
                style="width:222px"
              >
                {modifierTypeData.value.map((v: any) => (
                  <el-option
                    key={v.value}
                    label={v.label}
                    value={v.value}
                  ></el-option>
                ))}
              </el-select>
            </el-form-item>

            <el-form-item
              label="修饰词名称:"
              prop="cnName"
              error={errCheck('cnName')}
            >
              <el-input
                size="large"
                disabled={isEdits}
                placeholder="请输入"
                v-model={model.cnName}
                style="width:222px"
              />
            </el-form-item>

            <el-form-item
              label="修饰词英文名:"
              prop="enName"
              error={errCheck('enName')}
            >
              <el-input
                size="large"
                disabled={isEdits}
                placeholder="请输入"
                v-model={model.enName}
                style="width:222px"
              />
            </el-form-item>

            <el-form-item label="主题:" prop="subjectId">
              <el-select
                size="large"
                v-model={model.subjectId}
                filterable
                placeholder="请选择"
                style="width:222px"
              >
                {subjectList.value.map((v: any) => (
                  <el-option
                    key={v.id}
                    label={v.subjectName}
                    value={v.id}
                  ></el-option>
                ))}
              </el-select>
            </el-form-item>

            <el-form-item label="修饰词分组:" prop="groupId">
              <el-cascader
                v-model={model.groupId}
                options={gourpOptions.value?.children}
                props={{ label: 'name', value: 'id' }}
                onChange={(v: any) => {
                  model.groupId = v[v.length - 1];
                }}
              />
            </el-form-item>

            <el-form-item label="业务含义:" prop="businessMeaning">
              <el-input
                style="width:424px;height:100px"
                placeholder="请输入"
                v-model={model.businessMeaning}
                type="textarea"
              />
            </el-form-item>

            <el-form-item label="代码片段:" prop="codeSegment">
              <el-input
                style="width:424px;height:100px"
                placeholder="请输入"
                v-model={model.codeSegment}
                type="textarea"
              />
            </el-form-item>

            <el-form-item label="备注:" prop="remarks">
              <el-input
                style="width:424px;height:100px"
                placeholder="请输入"
                v-model={model.remarks}
                type="textarea"
              />
            </el-form-item>
          </el-form>
          <div class="footer-btn">
            <el-button onClick={() => emit('handleClose')}>取消</el-button>
            <el-button type="primary" onClick={() => emit('submit', model)}>
              确定
            </el-button>
          </div>
        </div>
      );
    };
  }
});

export default createForm;
